package com.test2.opencv;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.DataBufferByte;

public class TestMatch2 {

    static int CVTYPE= CvType.CV_8UC4;

    static void findimg(Mat source) {
        //将文件读入为OpenCV的Mat格式
        //被匹配的文件
        Mat template = Imgcodecs.imread("d:\\1T.jpg");
        //创建于原图相同的大小，储存匹配度
        Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CVTYPE);
        //调用模板匹配方法
        int method= Imgproc.TM_CCORR_NORMED;
        Imgproc.matchTemplate(source, template, result,method);
        //规格化
        Core.normalize(template, template, 0, 1, Core.NORM_MINMAX, -1);
        //获得最可能点，MinMaxLocResult是其数据格式，包括了最大、最小点的位置x、y
        Core.MinMaxLocResult mlr = Core.minMaxLoc(result);

        Point matchLoc;

        //根据匹配算法选择匹配结果
        if (method==Imgproc.TM_SQDIFF||method==Imgproc.TM_SQDIFF_NORMED) {
            matchLoc = mlr.minLoc;
            System.out.println(" mlr.min="+mlr.minVal);//匹配度
            //在原图上的对应模板可能位置画一个绿色矩形
            System.out.println(matchLoc.x + template.width()+"  "+matchLoc.y+template.height());
            Imgproc.rectangle(source, matchLoc, new Point(matchLoc.x + template.width(), matchLoc.y + template.height()), new Scalar(0, 255, 0));
        }
        else {
            matchLoc = mlr.maxLoc;
            System.out.println("mlr.max="+mlr.maxVal);//匹配度
            //在原图上的对应模板可能位置画一个绿色矩形
            System.out.println(matchLoc.x + template.width()+"  "+matchLoc.y+template.height());
            Imgproc.rectangle(source, matchLoc, new Point(matchLoc.x + template.width(), matchLoc.y + template.height()), new Scalar(0, 255, 0));
        }

        //将匹配结果输出为e.jpg 画绿色框
        Imgcodecs.imwrite("d:\\test2.png", source);

    }

    public static Mat getScreenShot() {

        int captureWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int captureHeight = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        BufferedImage bfImage =   new BufferedImage(captureWidth, captureHeight,      BufferedImage.TYPE_3BYTE_BGR);
        try {
            Robot robot = new Robot();

            Rectangle screenRect = new Rectangle(0,0,captureWidth,captureHeight);
            bfImage = robot.createScreenCapture(screenRect);

        } catch (AWTException e) {
            e.printStackTrace();
        }

        Mat mat =  new Mat(bfImage.getHeight(), bfImage.getWidth(), CvType.CV_8UC3);

        mat.put(0, 0,getMatrixRGB(bfImage));

        return mat;
    }

    /**
     * 获取图像RGB格式数据
     * @param image
     * @return
     */
    public static byte[] getMatrixRGB(BufferedImage image){
        if(image.getType()!=BufferedImage.TYPE_3BYTE_BGR){
            // 转sRGB格式
            BufferedImage rgbImage = new BufferedImage(
                    image.getWidth(),
                    image.getHeight(),
                    BufferedImage.TYPE_3BYTE_BGR);
            new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(image, rgbImage);
            // 从Raster对象中获取字节数组

            return  (byte[])((DataBufferByte)rgbImage.getRaster().getDataBuffer()).getData();
//            return (byte[]) rgbImage.getData().getDataElements(0, 0, rgbImage.getWidth(), rgbImage.getHeight(), null);
        }else{
            return (byte[]) image.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
        }
    }



    public static void main(String[] args) {
        nu.pattern.OpenCV.loadShared();
//        nu.pattern.OpenCV.loadLocally();
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
       // findimg( getScreenShot());
         findimg(Imgcodecs.imread("d:\\1S.jpg"));

    }
}
